<%@page import="java.io.*" %>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="com.google.gson.*"%>
<%@page pageEncoding="UTF-8"%>
<%!
public  class TreeNode
{
	String id;
	String text;
	boolean expanded;
	List<TreeNode> children = new ArrayList<TreeNode>();
	public TreeNode()
	{
		super();
	}
	public TreeNode(String id, String text, boolean expanded,
			List<TreeNode> children)
	{
		super();
		this.id = id;
		this.text = text;
		this.expanded = expanded;
		this.children = children;
	}
	public String getId()
	{
		return id;
	}
	public String getText()
	{
		return text;
	}
	public boolean isExpanded()
	{
		return expanded;
	}
	public void setId(String id)
	{
		this.id = id;
	}
	public void setText(String text)
	{
		this.text = text;
	}
	public void setExpanded(boolean expanded)
	{
		this.expanded = expanded;
	}
	public List<TreeNode> getChildren()
	{
		return children;
	}
	public void setChildren(List<TreeNode> children)
	{
		this.children = children;
	}
}
%>

<%!
	public class FileService
{
	private String root;
	public FileService()
	{
		this("");
	}
	public FileService(String root)
	{
		this.root=root;
	}
	
	public String getRoot()
	{
		return root;
	}
	public String idToPath(String id)
	{
		if(id.equals("root"))
		{
			return root;
		}
		else
		{
			return id.replaceFirst("root", root);
		}
	}
	public String pathToId(String path)
	{
		if(path.equals(root))
		{
			return "root";
		}
		else
		{
			//replaceFirst 有问题
			return "root"+path.substring(root.length());
		}
	}
	
	
	private List<TreeNode> getChildren(String id)
	{
		List<TreeNode> children = new ArrayList<TreeNode>();
		String path = idToPath(id);
		File f = new File(path);
		if(!f.exists())
			return children;
		for(File subfile:f.listFiles())
		{
			if(subfile.isDirectory())
			{
				TreeNode child = new TreeNode();
				child.setExpanded(true);
				child.setId(pathToId(subfile.getAbsolutePath()));
				child.setText(subfile.getName());
				TreeNode node = new TreeNode();
				child.getChildren().add(node);
				children.add(child);
				
			}
		}
		return children;
	}
	
	public String getTree(String id)
	{
		Gson gson = new Gson();
		return gson.toJson(getChildren(id));
	}
}
%>

<%
	
	String path = request.getSession().getServletContext()
									 .getRealPath("resource-test/校本资源");
	FileService service = new FileService(path);
	out.print(service.getTree("root"));
	
	
%>
    